package com.mianyang.zhangsan.plugin.quartz.util;

import com.mianyang.zhangsan.common.util.JsonUtils;
import com.mianyang.zhangsan.model.entity.SecTask;
import com.mianyang.zhangsan.plugin.quartz.contant.TaskType;
import com.mianyang.zhangsan.service.ISecSpringContextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author jiangjr
 * @date 2022-11-23
 */
@Slf4j
@Component
public class QuartzExecuteHelper {
    @Autowired
    private ISecSpringContextService springContextService;

    public Object invoke(SecTask task) {
        Object invoke;
        Object instance;
        try {
            TaskType taskType = TaskType.valueOf(task.getTaskGroup());
            instance = springContextService.getBean(taskType.getBeanName());
            Method method = instance.getClass().getMethod(taskType.getMethodName(), Map.class);
            invoke = method.invoke(instance, parseParam(task.getTaskParam()));
        } catch (Exception e) {
            log.error("任务执行异常");
            throw new RuntimeException("任务执行异常");
        }
        return invoke;
    }

    private static Map<String, Object> parseParam(String param) {
        return JsonUtils.toMap(param, String.class, Object.class);
    }
}
